#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

#define TASK_NUM 5

typedef void (*task_t)();

void download()
{
    printf("A download task is running!\n");
}

void printlog()
{
    printf("A printlog task is running!\n");
}

void show()
{
    printf("A show task is running!\n");
}

void initTask(task_t tasks[], int num)
{
    for(int i = 0;i < num; i++)
    {
        tasks[i] = NULL;
    }
}

int addTask(task_t tasks[], task_t t)
{
    for(int i = 0; i < TASK_NUM; i++)
    {
        if(tasks[i] == NULL)
        {
            tasks[i] = t;
            return 1;
        }
    }
    return 0;
}

void executeTask(task_t tasks[], int num)
{
    for(int i = 0; i < num; i++)
    {
        if(tasks[i] != NULL)
        {
            tasks[i]();
        }
    }

}

void Worker(int cnt)
{
    printf("I am a child process!, pid: %d, cnt: %d\n", getpid(), cnt);
}

int main()
{
    task_t tasks[TASK_NUM];
    initTask(tasks, TASK_NUM);
    addTask(tasks, download);
    addTask(tasks, printlog);
    addTask(tasks, show);

    pid_t id = fork();
    if(0 == id)
    {
        int cnt = 5;
        while(cnt)
        {
            Worker(cnt);
            sleep(2);
            cnt--;
        }
    }
    
    //father
    int status = 0;
    while(1) //轮询式非阻塞等待
    {
        pid_t rid = waitpid(id, &status, WNOHANG);
        if(rid > 0)
        {
            //wait success, child quit now!
            printf("child quit sucess, exit code: %d, exit signal: %d\n", (status>>8)&0xFF, status&0X7F);
            break;
        }
        else if(rid == 0)
        {
            //wait success, but child not quit
            printf("###############################################");
            printf("child is alive, wait again, father do other things!\n");
            executeTask(tasks, TASK_NUM);
            printf("###############################################");
        }
        else
        {
            printf("wait failed!\n");
            break;
        }
        sleep(1);
    }
}

